﻿#include "user-ProductList.h"

UserProductList::UserProductList(database &db, QWidget *parent)
    : QWidget(parent), db(db)
{
    // 创建页面布局
    QVBoxLayout *mainLayout = new QVBoxLayout(this);

    // 创建顶部区域
    QWidget *topWidget = new QWidget(this);
    QHBoxLayout *topLayout = new QHBoxLayout(topWidget);

    // 返回按钮
    backButton = new QPushButton("返回首页", this);
    backButton->setFont(QFont("", 12, QFont::Bold));
    backButton->setMinimumHeight(40);
    connect(backButton, &QPushButton::clicked, this, &UserProductList::backButtonClicked);
    // 商户信息标签
    businessInfoLabel = new QLabel("商户商品", this);
    businessInfoLabel->setStyleSheet("font-size: 18pt; font-weight: bold;");

    topLayout->addWidget(backButton);
    topLayout->addWidget(businessInfoLabel, 1);
    topLayout->addStretch();

    // 创建商品表格
    productsTable = new QTableWidget(0, 5, this);
    productsTable->setHorizontalHeaderLabels({"图片", "商品名称", "价格", "销量", "操作"});

    // 设置表格样式（美化）
    productsTable->setStyleSheet(
        "QTableWidget {"
        "  border: 1px solid #e0e0e0;"
        "  border-radius: 10px;"
        "  background: #fafbfc;"
        "  font-size: 16px;"
        "}"
        "QHeaderView::section {"
        "  background: #f5f5f5;"
        "  font-weight: bold;"
        "  border: none;"
        "  padding: 10px;"
        "  font-size: 15px;"
        "}"
        "QTableWidget::item {"
        "  padding: 12px;"
        "  border-bottom: 1px solid #e0e0e0;"
        "}"
        "QTableCornerButton::section {"
        "  background: #f5f5f5;"
        "  border: none;"
        "}"
    );
    productsTable->setAlternatingRowColors(true);
    productsTable->setStyleSheet(productsTable->styleSheet() +
        "QTableWidget { alternate-background-color: #f7f7fa; }"
    );
    // 设置表头字体
    QFont headerFont = productsTable->horizontalHeader()->font();
    headerFont.setPointSize(12);
    headerFont.setBold(true);
    productsTable->horizontalHeader()->setFont(headerFont);
    productsTable->horizontalHeader()->setMinimumHeight(40);

    // 创建购物车对象
    cart = new UserCart(db, this);
    
    // 创建购物车控件
    cartWidget = new CartWidget(cart, this);
    
    // 连接购物车控件的openProfilePage信号
    connect(cartWidget, &CartWidget::openProfilePage, this, &UserProductList::openProfilePage);

    // 添加到主布局
    mainLayout->addWidget(topWidget);
    mainLayout->addWidget(productsTable, 1);
    mainLayout->addWidget(cartWidget);

    // 美化底部购物车控件区域（如果有）
    if (cartWidget) {
        cartWidget->setStyleSheet(
            "QWidget {"
            "  background: #f5f5f5;"
            "  border-top: 1px solid #e0e0e0;"
            "  border-radius: 0 0 10px 10px;"
            "  padding: 12px 24px;"
            "  font-size: 16px;"
            "}"
            "QPushButton {"
            "  background: #ff9800;"
            "  color: white;"
            "  border-radius: 8px;"
            "  padding: 8px 24px;"
            "  font-size: 18px;"
            "}"
            "QPushButton:disabled {"
            "  background: #ffe0b2;"
            "  color: #aaa;"
            "}"
        );
    }
}

UserProductList::~UserProductList()
{
}
void UserProductList::setPhone_id(int phone_id){
    this->phone_id = phone_id;
    qDebug()<<"60-UserProductList:"<<phone_id;
    cartWidget->setPhoneId(phone_id);
}
void UserProductList::loadBusinessProducts(const QString &businessName, int businessId)
{
    // 清空购物车
    cart->clear();
    
    // 更新商户信息标签
    businessInfoLabel->setText(businessName + " - 商品列表");

    // 清空表格
    productsTable->setRowCount(0);
    
    // 查询商家营业状态
    int businessStatus = 1;
    QString statusSql = QString("SELECT status FROM business WHERE business_id = %1").arg(businessId);
    QSqlQuery statusQuery = db.exec(statusSql);
    if (statusQuery.next()) {
        businessStatus = statusQuery.value(0).toInt();
    }
    // 查询配送费
    double deliveryFee = 0.0;
    QString deliverySql = QString("SELECT delivery FROM business WHERE business_id = %1").arg(businessId);
    QSqlQuery deliveryQuery = db.exec(deliverySql);
    if (deliveryQuery.next()) {
        deliveryFee = deliveryQuery.value(0).toDouble();
    }
    
    // 设置商户信息和配送费
    cart->setBusinessInfo(businessId, deliveryFee);

    // 查询商品
    QString sql;
    if (businessId > 0) {
        sql = QString("SELECT c.com_id, c.com_name, c.price, c.number, c.img FROM commodity c "
                     "WHERE c.business_id = %1 AND c.cs_id = 3" ).arg(businessId);
    } else {
        sql = QString("SELECT c.com_id, c.com_name, c.price, c.number, c.img FROM commodity c "
                     "JOIN business b ON c.business_id = b.business_id "
                     "WHERE b.business_name = '%1' AND c.cs_id = 3").arg(businessName);
    }

    QSqlQuery query = db.exec(sql);
    int row = 0;

    while(query.next()) {
        int productId = query.value(0).toInt();
        QString productName = query.value(1).toString();
        double price = query.value(2).toDouble();
        int stock = query.value(3).toInt();
        QString imgPath = query.value(4).toString();

        productsTable->insertRow(row);

        // 图片单元格
        QLabel *imgLabel = new QLabel();
        imgLabel->setObjectName("imgLabel");
        QString defaultImg = ":/img/bilibili.png";
        QString showPath = (!imgPath.isEmpty() && QFile::exists(imgPath)) ? imgPath : defaultImg;
        QPixmap pixmap(showPath);
        if (!pixmap.isNull()) {
            pixmap = pixmap.scaled(80, 80, Qt::KeepAspectRatio, Qt::SmoothTransformation);
            imgLabel->setPixmap(pixmap);
        } else {
            imgLabel->setText("无图片");
        }
        imgLabel->setAlignment(Qt::AlignCenter);
        imgLabel->setStyleSheet(
            "QLabel#imgLabel {"
            "  border-radius: 8px;"
            "  border: 1px solid #ddd;"
            "  background: #fff;"
            "  padding: 2px;"
            "}");
        productsTable->setCellWidget(row, 0, imgLabel);

        // 商品名称
        QTableWidgetItem *nameItem = new QTableWidgetItem(productName);
        nameItem->setTextAlignment(Qt::AlignCenter);
        nameItem->setFont(QFont("", 12, QFont::Bold));
        productsTable->setItem(row, 1, nameItem);

        // 价格
        QTableWidgetItem *priceItem = new QTableWidgetItem(QString::number(price, 'f', 2) + " 元");
        priceItem->setTextAlignment(Qt::AlignCenter);
        priceItem->setFont(QFont("", 11));
        productsTable->setItem(row, 2, priceItem);

        // 销量（原库存）
        QTableWidgetItem *stockItem = new QTableWidgetItem(QString::number(stock));
        stockItem->setTextAlignment(Qt::AlignCenter);
        stockItem->setFont(QFont("", 11));
        productsTable->setItem(row, 3, stockItem);

        // 创建操作区域（加减按钮和数量显示）
        QWidget *operationWidget = new QWidget();
        QHBoxLayout *operationLayout = new QHBoxLayout(operationWidget);
        operationWidget->setStyleSheet(
            "QWidget { background: transparent; }"
        );
        
        // 减少按钮
        QPushButton *minusButton = new QPushButton("-", this);
        minusButton->setFixedSize(36, 36);
        minusButton->setFont(QFont("", 14, QFont::Bold));
        minusButton->setStyleSheet(
            "QPushButton {"
            "   background-color: #f44336;"
            "   color: white;"
            "   border-radius: 18px;"
            "   border: none;"
            "   font-size: 20px;"
            "}"
            "QPushButton:disabled {"
            "   background-color: #ffcdd2;"
            "   color: #666666;"
            "}"
        );
        minusButton->setEnabled(false); // 初始状态禁用
        
        // 数量标签
        QLabel *quantityLabel = new QLabel("0", this);
        quantityLabel->setAlignment(Qt::AlignCenter);
        quantityLabel->setFixedWidth(40);
        quantityLabel->setFont(QFont("", 14, QFont::Bold));
        quantityLabel->setStyleSheet(
            "QLabel {"
            "   background: #f5f5f5;"
            "   border-radius: 8px;"
            "   border: 1px solid #e0e0e0;"
            "   color: #333;"
            "   font-size: 18px;"
            "   min-height: 32px;"
            "}");
        
        // 增加按钮
        QPushButton *plusButton = new QPushButton("+", this);
        plusButton->setFixedSize(36, 36);
        plusButton->setFont(QFont("", 14, QFont::Bold));
        plusButton->setStyleSheet(
            "QPushButton {"
            "   background-color: #4CAF50;"
            "   color: white;"
            "   border-radius: 18px;"
            "   border: none;"
            "   font-size: 20px;"
            "}"
            "QPushButton:hover {"
            "   background-color: #45a049;"
            "}"
        );
        
        // 设置按钮属性
        minusButton->setProperty("productId", productId);
        minusButton->setProperty("row", row);
        plusButton->setProperty("productId", productId);
        plusButton->setProperty("row", row);
        
        // 连接按钮信号
        connect(minusButton, &QPushButton::clicked, [this, productId, row, quantityLabel, minusButton]() {
            // 更新购物车中的数量
            cart->updateQuantity(productId, "", 0, -1);
            
            // 更新UI显示
            int quantity = cart->getQuantity(productId);
            quantityLabel->setText(QString::number(quantity));
            
            // 更新减号按钮状态
            minusButton->setEnabled(quantity > 0);
        });
        
        connect(plusButton, &QPushButton::clicked, [this, productId, row, productName, price, quantityLabel, minusButton]() {
            // 更新购物车中的数量
            cart->updateQuantity(productId, productName, price, 1);
            
            // 更新UI显示
            int quantity = cart->getQuantity(productId);
            quantityLabel->setText(QString::number(quantity));
            
            // 更新减号按钮状态
            minusButton->setEnabled(quantity > 0);
        });
        
        operationLayout->addWidget(minusButton);
        operationLayout->addWidget(quantityLabel);
        operationLayout->addWidget(plusButton);
        operationLayout->setContentsMargins(5, 5, 5, 5);
        operationLayout->setSpacing(8);
        productsTable->setCellWidget(row, 4, operationWidget);

        // 设置行高
        productsTable->setRowHeight(row, 110);

        row++;
    }

    // 调整列宽
    productsTable->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Fixed);
    productsTable->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch);
    productsTable->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Fixed);
    productsTable->horizontalHeader()->setSectionResizeMode(3, QHeaderView::Fixed);
    productsTable->horizontalHeader()->setSectionResizeMode(4, QHeaderView::Fixed);
    productsTable->setColumnWidth(0, 280);
    productsTable->setColumnWidth(2, 200);
    productsTable->setColumnWidth(3, 180);
    productsTable->setColumnWidth(4, 200);

    // 禁用购物车下单按钮（如果商家休息）
    cartWidget->setEnabled(businessStatus == 1);
    if (businessStatus == 0) {
        businessInfoLabel->setText(businessName + " - 商家休息中，暂不可下单");
    }
}

void UserProductList::updateProductQuantityUI(int row, int quantity)
{
    // 获取操作区域控件
    QWidget *operationWidget = productsTable->cellWidget(row, 4);
    if (!operationWidget) return;
    
    // 获取数量标签和减号按钮
    QLabel *quantityLabel = operationWidget->findChild<QLabel*>();
    QPushButton *minusButton = operationWidget->findChildren<QPushButton*>().first();
    
    if (quantityLabel && minusButton) {
        quantityLabel->setText(QString::number(quantity));
        minusButton->setEnabled(quantity > 0);
    }
} 
